package BarCode;

import java.util.HashMap;
import java.util.Map;

public class BarCode {

    static Map<String, String> barCodeToNumMap = new HashMap<String, String>();

    static {
        barCodeToNumMap.put(":::||","1");
        barCodeToNumMap.put("::|:|","2");
        barCodeToNumMap.put("::||:","3");
        barCodeToNumMap.put(":|::|","4");
        barCodeToNumMap.put(":|:|:","5");
        barCodeToNumMap.put(":||::","6");
        barCodeToNumMap.put("|:::|","7");
        barCodeToNumMap.put("|::|:","8");
        barCodeToNumMap.put("|:|::","9");
        barCodeToNumMap.put("||:::","0");
    }

    public static boolean isValidBarCode(String s) {
        if (s.length() % (5*6) != 2 && s.length() % (5*10) != 2 && s.length() % (5*11) != 2) {
            throw new RuntimeException("Error bar-code, this bar-code length is error.");
        }
        if (!s.startsWith("|") || !s.endsWith("|")) {
            throw new RuntimeException("Error bar-code, this bar-code format is invalid.");
        }

        int barCodeSum = 0;
        String barCodeStr = s.substring(1, s.length() - 1);
        for (int i = 0; i * 5 < barCodeStr.length() ; i ++) {
            String barNum = barCodeStr.substring(i*5,i*5+5);
            if (!barCodeToNumMap.containsKey(barNum)) {
                throw new RuntimeException("Error bar-code, this bar-code has invalid bar num.");
            }
            barCodeSum = barCodeSum + Integer.parseInt(barCodeToNumMap.get(barNum));
        }

        if (0 != barCodeSum && barCodeSum % 10 != 0) {
            throw new RuntimeException("Error bar-code, this bar-code has a error check code.");
        }

        return true;
    }

    public static String toPostCode(String s) {
        StringBuffer postCode = new StringBuffer();
        String barCodeStr = s.substring(1, s.length() - 1 - 5);
        for (int i = 0; i * 5 < barCodeStr.length() ; i ++) {
            String barNum = barCodeStr.substring(i*5,i*5+5);
            postCode.append(barCodeToNumMap.get(barNum));
        }
        if (postCode.length() == 9) {
            postCode.insert(5,'-');
        }
        return postCode.toString();
    }
}
